package com.kaikai.educenter.controller;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.kaikai.commonutils.JwtUtils;
import com.kaikai.educenter.entity.UcenterMember;
import com.kaikai.educenter.service.UcenterMemberService;
import com.kaikai.educenter.utils.ConstantPropertiesUtil;
import com.kaikai.educenter.utils.HttpClientUtils;
import com.kaikai.servicebase.exceptionhandler.MyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.net.URLEncoder;
import java.util.HashMap;

@CrossOrigin
@Controller
@RequestMapping("api/ucenter/wx")
public class WxApiController {

    @Autowired
    UcenterMemberService ucenterMemberService;

    /**
     *  //回调方法,调用微信api获取扫码得到的code获取用户名称
     * @param code
     * @param state
     * @return
     */
    @GetMapping("callback")
    public String callback(String code,String state){
        //从redis中将state获取出来，和当前传入的state作比较
        //如果一致则放行，如果不一致则抛出异常：非法访问
try {
    //向认证服务器发送请求换取access_token
    String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
            "?appid=%s" +
            "&secret=%s" +
            "&code=%s" +
            "&grant_type=authorization_code";

    String accessTokenUrl = String.format(baseAccessTokenUrl,
            ConstantPropertiesUtil.WX_OPEN_APP_ID,
            ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
            code);
    /**
     * 1.通过httpClient访问api得到的字符串(其中需要openid和access_token的值)
     */

    //返回结果是个json字符串
    String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
    //将json字符串中所需值转换为map后取出
    Gson gson=new Gson();
     HashMap accessMap = gson.fromJson(accessTokenInfo, HashMap.class);
     String openid = (String) accessMap.get("openid");

    //查找用户 添加操作
    UcenterMember member = ucenterMemberService.getById(openid);
    if(member==null){


     String accessToken = (String) accessMap.get("access_token");
    /**
     *2.用获取的两个值再去调用另一个api,获取微信扫描人信息,例如头像昵称
     */

    //访问微信的资源服务器，获取用户信息
    String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
            "?access_token=%s" +
            "&openid=%s";
    String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
    String userInfo = HttpClientUtils.get(userInfoUrl);
    System.out.println(userInfo);
     HashMap mapUserInfo = gson.fromJson(userInfo, HashMap.class);
        String nickname=(String) mapUserInfo.get("nickname");
        String headimgurl=(String) mapUserInfo.get("headimgurl");

        member=new UcenterMember();
        member.setNickname(nickname);
        member.setAvatar(headimgurl);
        member.setOpenid(openid);
        ucenterMemberService.save(member);

    }
    String token= JwtUtils.getJwtToken(member.getId(), member.getNickname());
    System.out.println("用户名:"+ member.getNickname());
    System.out.println(token);
    return "redirect:http://localhost:3000?token="+token;

    }catch(Exception e){
    e.printStackTrace();
    throw new MyException(20001,"登陆失败");
}
    }



    @GetMapping("getCode")
    //1.生成微信扫描二维码
    public  String  getWxCode(){
        //https://open.weixin.qq.com/connect/qrconnect?
        // appid=APPID
        // &redirect_uri=REDIRECT_URI
        // &response_type=code
        // &scope=SCOPE
        // &state=STATE
        // #wechat_redirect

        String url=null;
        try {
        String BaseUrl="https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        //请使用urlEncode对链接进行处理

            String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
                redirectUrl = URLEncoder.encode(redirectUrl, "utf-8");
            url = String.format(
                    BaseUrl,
                    ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    redirectUrl,
                    "kaikai"
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:"+url;

    }
}
